package fm.admin.controller;

import com.mongodb.DBObject;
import fm.cache.ConfigCache;
import fm.controller.BaseController;
import fm.dto.GoodClassDto;
import fm.entityEnum.CarouselScope;
import fm.entityEnum.CarouselType;
import fm.entityEnum.CollectTypeEnum;
import fm.exception.BizException;
import fm.exception.TokenInvalidException;
import fm.fmEnum.GoodFlag;
import fm.mongo.MCondition;
import fm.mongo.MRel;
import fm.util.CommonUtils;
import fm.web.CurrentRequest;
import fm.web.MediaTypes;
import fm.yichenet.mongo.service.CarouselService;
import fm.yichenet.mongo.service.GoodMgrService;
import fm.yichenet.mongo.service.ShopMgrService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @修改人：CM
 * @修改时间：2017/3/15 13:17
 */
@Controller
@RequestMapping("/shop")
public class ShopMgrController extends BaseController {
    @Autowired
    private ShopMgrService shopMgrService;
    @Autowired
    private GoodMgrService goodMgrService;
    @Autowired
    CarouselService carouselService;
    @RequestMapping("/index")
    public  String  shopIndex(ModelMap modelMap) throws Exception{
        return "admin/shop/shopSet";
    }
    @RequestMapping("/home")
    public String index(ModelMap modelMap) throws Exception {
        Map param = new HashMap();
        param.put("uuid", getCurrentUserId());
        List<String> flags = new ArrayList<>();
        flags.add(GoodFlag.HOME_AD.getDesc());
        param.putAll(MCondition.create(MRel.in).append("flag", flags).toDBObject().toMap());
        List<DBObject> adGoods = goodMgrService.getList(param, null, null,null);
        modelMap.put("adGoods", adGoods);

        Map param1 = new HashMap();
        param1.put("uuid", getCurrentUserId());
        List<String> flags1 = new ArrayList<>();
        flags1.add(GoodFlag.HOME_NEW.getDesc());
        param1.putAll(MCondition.create(MRel.in).append("flag", flags1).toDBObject().toMap());
        List<DBObject> newGoods = goodMgrService.getList(param1, null, null,null);
        modelMap.put("newGoods", newGoods);

        Map param2 = new HashMap();
        param2.put("uuid", getCurrentUserId());
        List<String> flags2 = new ArrayList<>();
        flags2.add(GoodFlag.HOME_HOT.getDesc());
        param2.putAll(MCondition.create(MRel.in).append("flag", flags2).toDBObject().toMap());
        List<DBObject> hotGoods = goodMgrService.getList(param2, null, null,null);
        modelMap.put("hotGoods", hotGoods);
        modelMap.put("config", shopMgrService.getHomeConfig(param2));
        return "admin/shop/home";
    }

    @RequestMapping("/good/type")
    public String goodTypeMgr(ModelMap modelMap) {
        return "admin/shop/goodClass";
    }

    @ResponseBody
    @RequestMapping(value = "/good/type/data", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map productList(ModelMap modelMap) {
        Map response = new HashMap();
        try {
            Map param = getEmptyParamMap();
            String defaultUuid = ConfigCache.getConfig("DEFAULT_UUID");
            if (StringUtils.isEmpty(defaultUuid)) {
                throw new BizException("default uuid un-config!");
            }
            param.put("uuid",defaultUuid);
            //biz code here
            DBObject classes = shopMgrService.getGoodClassByUuid(param);
            response.put("data", classes);
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "good/type/addOrUpdate", method = RequestMethod.POST)
    public Map updateGoodClassesConfig(@RequestBody GoodClassDto data) {
        Map response = new HashMap();
        try {
            Map param = getEmptyParamMap();
            String defaultUuid = ConfigCache.getConfig("DEFAULT_UUID");

            param.put("uuid", defaultUuid);
            DBObject config = shopMgrService.getGoodClassByUuid(param);
            if (data != null) {
                param.put("list", data);
                if (config != null) {
                    shopMgrService.updateGoodClass(param);
                } else {
                    shopMgrService.addGoodClass(param);
                }
                this.success(response);
            } else {
                throw new RuntimeException("类别配置不能为空");
            }

        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;
    }


    /**
     * 关于我们界面配置与管理
     * 配置地图位置
     * 展示已经存在的联系信息
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/about")
    public String aboutMgr(ModelMap modelMap,
                           @RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        List<DBObject> contactInfos = shopMgrService.getContactInfoByPage(pageNum, pageSize);
        Map param = new HashMap();
        param.put("uuid", getCurrentUserId());
        DBObject aboutConfig = shopMgrService.getAboutConfig(param);
        modelMap.put("config", aboutConfig);
        modelMap.put("contacts", contactInfos);
        return "/admin/shop/about";
    }

    @ResponseBody
    @RequestMapping(value = "/map/config/save", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map productList(ModelMap modelMap, String lat, String lng, String desc, String tip) {
        Map response = new HashMap();
        try {
            Map param = getEmptyParamMap();
            param.put("uuid", getCurrentUserId());
            if (StringUtils.isNotBlank(lat)) {
                param.put("lat", lat);
            }
            if (StringUtils.isNotBlank(lng)) {
                param.put("lng", lng);
            }
            if (StringUtils.isNotBlank(desc)) {
                desc = URLDecoder.decode(desc, "UTF-8");
                param.put("desc", desc);
            }
            if (StringUtils.isNotBlank(tip)) {
                tip = URLDecoder.decode(tip, "UTF-8");
                param.put("tip", tip);
            }
            shopMgrService.updateMapConfig(param);
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/about/content/save", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map aboutContentUpdate(String content) {
        Map response = new HashMap();
        try {
            Map param = getEmptyParamMap();
            param.put("uuid", getCurrentUserId());
            if (StringUtils.isNotEmpty(content)) {
                content = URLDecoder.decode(content, "UTF-8");
                param.put("content", content);
            }
            shopMgrService.updateAboutContent(param);
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;
    }

    /**
     *
     * @param uri
     * @param type
     * @param typeValue
     * @return
     */
        @ResponseBody
         @RequestMapping(value = "carousel/add",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
         public Map addShopCarousel(String uri , CarouselType type,String typeValue,String shopId){
             Map res = new HashMap();
             try{
                 if (StringUtils.isEmpty(uri)) {
                     throw new BizException("请先上传图片在添加");
                 }
                 if (StringUtils.isEmpty(typeValue)) {
                     throw new BizException("请选择/填入对应的" + type.getDesc());
                 }
                 DBObject object = carouselService.addShopCarousel(uri,type,typeValue,shopId);
                 res.put("data", object);
                 res.put("data","");
                 this.success(res);
             }catch (BizException ex){
                 LOGGER.error("发生错误:",ex);
                 this.failed(res,ex.getMessage());
             }catch (Exception ex){
                 LOGGER.error("发生异常",ex);
                 this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
             }
             return res;
         }
    @ResponseBody
    @RequestMapping("/carousel/del")
    public Map delShopCarousel(String cid) {
        Map res = new HashMap();
        try {
            if (StringUtils.isEmpty(cid)) {
                throw new BizException("未找到对应的轮播图，删除失败");
            }
            carouselService.delShopCarousel(cid);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }
    @ResponseBody
    @RequestMapping("/carousel/list")
    public Map carouselList(CarouselType type, String  shopId) {
        Map res = new HashMap();
        try {
            List<DBObject> list = carouselService.getShopCarouselList(type,shopId);
            res.put("data", list);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }
       @ResponseBody
        @RequestMapping(value = "brandflag/{action}",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
        public Map brandFlag(@PathVariable String action,String brandName,String brandLogo,String shopId){
            Map res = new HashMap();
            try{
                shopMgrService.agencyBrandMg(action,brandName,brandLogo,shopId);
                res.put("data","");
                this.success(res);
            }catch (BizException ex){
                LOGGER.error("发生错误:",ex);
                this.failed(res,ex.getMessage());
            }catch (Exception ex){
                LOGGER.error("发生异常",ex);
                this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
            }
            return res;
        }
           @ResponseBody
            @RequestMapping(value = "agencyBrand/list",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
            public Map geyAgencyBrandList(String shopId){
                Map res = new HashMap();
                try{
                    if(!CurrentRequest.isAdmin()){
                        shopId = getCurrentUserId();
                    }
                    List brandList = shopMgrService.getAgencyBrandList(shopId);
                    res.put("data",brandList);
                    this.success(res);
                }catch (BizException ex){
                    LOGGER.error("发生错误:",ex);
                    this.failed(res,ex.getMessage());
                }catch (Exception ex){
                    LOGGER.error("发生异常",ex);
                    this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
                }
                return res;
            }

    /**
     * 获取收藏列表
     * @param user_id
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "loadCollect",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public Map loadCollect(String user_id, CollectTypeEnum type){
        Map res = new HashMap();
        try{
            if(CommonUtils.isEmpty(user_id)){
                user_id= (String) CurrentRequest.getCurrentUserId();
            }
            List<DBObject> collectList = shopMgrService.getCollectList(user_id,type);
            res.put("data",collectList);
            this.success(res);
        }catch (BizException ex){
            LOGGER.error("发生错误:",ex);
            this.failed(res,ex.getMessage());
        }catch (Exception ex){
            LOGGER.error("发生异常",ex);
            this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
        }
        return res;
    }

    /**
     * 删除收藏
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deleCollect",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public Map deleCollect(String id){
        Map res = new HashMap();
        try{
            if(CommonUtils.isEmpty(id)){
                LOGGER.error("发生错误:id为空");
            }
            shopMgrService.deleCollect(id);

            res.put("data",true);
            this.success(res);
        }catch (BizException ex){
            LOGGER.error("发生错误:",ex);
            this.failed(res,ex.getMessage());
        }catch (Exception ex){
            LOGGER.error("发生异常",ex);
            this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
        }
        return res;
    }

    /**
     * 收藏店铺
     */
        @ResponseBody
        @RequestMapping(value = "shopCollect",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
        public Map collectShopp(String shop_id,boolean flag){

            Map res = new HashMap();
            try{
                shopMgrService.shopCollect(shop_id,flag);
                res.put("data",true);
                this.success(res);
            }catch (BizException ex){
                LOGGER.error("发生错误:",ex);
                this.failed(res,ex.getMessage());
            }
            catch (Exception ex){
                LOGGER.error("发生异常",ex);
                this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
            }
            return res;
        }
}
